package com.bobo.cretrofit.interceptor;

import android.text.TextUtils;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * Okhttp 请求添加公共参数、公共Headers 方法
 * Created by cocolove2 on 2018/6/25.
 */
public abstract class CommonParamsInterceptor implements Interceptor {

    @NotNull
    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        Request.Builder requestBuilder = request.newBuilder();

        // process header params inject
        Headers.Builder headerBuilder = request.headers().newBuilder();
        // 以 Entry 添加消息头
        Map<String, String> buildHeaders = buildHeaderParams(request);
        if (buildHeaders != null && buildHeaders.size() > 0) {
            for (Map.Entry<String, String> entry : buildHeaders.entrySet()) {
                headerBuilder.add(entry.getKey(), entry.getValue());
            }
        }
        List<String> headerLines = buildHeaderLines(request);
        // 以 String 形式添加消息头
        if (headerLines != null && headerLines.size() > 0) {
            for (String line : headerLines) {
                headerBuilder.add(line);
            }
        }
        requestBuilder.headers(headerBuilder.build());
        // process header params end

        //构建公共参数
        Map<String, String> paramMap = buildParams(request);
        if (paramMap != null && paramMap.size() > 0) {
            //form表单提交
            if (canInjectIntoBody(request)) {
                // process post body inject
                //原有参数
                String postBodyString = bodyToString(request.body());
                FormBody.Builder formBodyBuilder = new FormBody.Builder();
                for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                    if (!postBodyString.contains(entry.getKey() + "=")) {
                        formBodyBuilder.add(entry.getKey(), entry.getValue());
                    }
                }
                RequestBody formBody = formBodyBuilder.build();
                postBodyString += ((postBodyString.length() > 0) ? "&" : "") + bodyToString(formBody);
                requestBuilder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"), postBodyString));
            } else {
                //查询参数
                // process queryParams inject whatever it's GET or POST
                injectParamsIntoUrl(request.url(), requestBuilder, paramMap);
            }
        }
        request = requestBuilder.build();
        return chain.proceed(request);
    }

    /**
     * 确认是否是 post 请求
     *
     * @param request 发出的请求
     * @return true 需要注入公共参数
     */
    private boolean canInjectIntoBody(Request request) {
        if (request == null) {
            return false;
        }
        if (!TextUtils.equals(request.method(), "POST")) {
            return false;
        }
        RequestBody body = request.body();
        if (body == null) {
            return false;
        }
        MediaType mediaType = body.contentType();
        if (mediaType == null) {
            return false;
        }
        return TextUtils.equals(mediaType.subtype(), "x-www-form-urlencoded");
    }

    // func to inject params into url
    private void injectParamsIntoUrl(HttpUrl url, Request.Builder requestBuilder, Map<String, String> paramsMap) {
        if (paramsMap.size() > 0) {
            HttpUrl.Builder httpUrlBuilder = url.newBuilder();
            Iterator<Map.Entry<String, String>> iterator = paramsMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                if (url.queryParameter(entry.getKey()) == null) {
                    httpUrlBuilder.addQueryParameter(entry.getKey(), entry.getValue());
                }
            }
            requestBuilder.url(httpUrlBuilder.build());
        }
    }

    private static String bodyToString(final RequestBody request) {
        try {
            final Buffer buffer = new Buffer();
            if (request != null)
                request.writeTo(buffer);
            else
                return "";
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }

    /**
     * 公共请求参数构建
     */
    public abstract Map<String, String> buildParams(Request request);

    /**
     * 公共请求头部参数构建
     */
    public Map<String, String> buildHeaderParams(Request request) {
        return null;
    }

    /**
     * 公共请求头部 (消息头 集合形式，一次添加一行)
     */
    public List<String> buildHeaderLines(Request request) {
        return null;
    }
}

